package com.hr.rbac.dao.Impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import org.junit.Test;

import com.hr.rbac.dao.PrivilegeDao;
import com.hr.rbac.domain.Privilege;
import com.hr.rbac.domain.Role;
import com.hr.utils.TxQueryRunner;

/**
 * 权限实现层
 * @author 杨谦
 * @date 2015-11-5
 *
 */
public class PrivilegeDaoImpl implements PrivilegeDao {

	private QueryRunner qr = new TxQueryRunner();
	
	@Override
	public List<Privilege> findByRoleId(String roleId) {
		// TODO Auto-generated method stub
		try {
			String sql_role_privilege = "select * from PRIVILEGE_ROLE where role_ID = ?";
			List<Object> privilegeID_List = qr.query(sql_role_privilege, new ColumnListHandler("privilege_ID"),roleId);
			List<Privilege> privileges = new ArrayList<Privilege>();
			for(int i = 0;i < privilegeID_List.size();i++) {
				privileges.add(findByPrivilegeID((String)privilegeID_List.get(i),roleId));
			}
			return privileges;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
		
	}

	@Override
	public Privilege findByPrivilegeID(String privilegeId) {
		
		try {
			String sql = "select * from HR_PRIVILEGE where privilege_ID = ?";
			return qr.query(sql, new BeanHandler<Privilege>(Privilege.class),privilegeId);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
		
	}
	
	@Override
	public Privilege findByPrivilegeID(String privilegeId,String role_id) {
		
		try {
			String sql = "select * from HR_PRIVILEGE where privilege_ID = ?";
			Privilege privilege = qr.query(sql, new BeanHandler<Privilege>(Privilege.class),privilegeId);
			privilege.setRole_id(role_id);
			return privilege;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
		
	}
	
	@Override
	public List<Privilege> queryAllPrivilege() {
		try {
			String sql = "select * from HR_PRIVILEGE";
			return qr.query(sql, new BeanListHandler<Privilege>(Privilege.class));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
	}
	
	@Test
	public void test() {
		System.out.println(queryAllPrivilege());
	}

}
